package icu.lookyousmileface.generatorandconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author starrysky
 * @title: GeneraAndConsumerSync
 * @projectName Juc_Pro
 * @description: juc版本生产者和消费者
 * @date 2021/1/299:11 上午
 * Condition+ flage标志位实现线程顺序执行
 */
public class GeneraAndConsumerJUC2 {
    public static void main(String[] args) {
        // 资源类
        Data2 data = new Data2();
        //线程
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.A();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.B();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.C();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

    }
}

class Data2{

    final Lock lock = new ReentrantLock();
    final Condition condition1 = lock.newCondition();
    final Condition condition2 = lock.newCondition();
    final Condition condition3 = lock.newCondition();
    private int flage = 1;


    public  void A() throws InterruptedException {
        lock.lock();
        try {
            //不是1就睡眠等待
            while (flage!=1){
                condition1.await();
            }
            flage++;
            System.out.println(Thread.currentThread().getName()+":"+"A");
            //唤醒指定的线程
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public  void B() throws InterruptedException {
        lock.lock();
        try {
            while (flage!=2){
                condition2.await();
            }
            flage++;
            System.out.println(Thread.currentThread().getName()+":"+"B");
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
        public  void C() throws InterruptedException {
            lock.lock();
            try {
                while (flage != 3) {
                    condition3.await();
                }
                flage=1;
                System.out.println(Thread.currentThread().getName() + ":" + "C");
                condition1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
}
